package com.pan.controller.interceptor;

import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.InterceptorException;
import com.pan.tools.RedisTools;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
public class SeckillCouponInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTools redisTools;

    /**
     * redis hash
     *     key: seckillCoupon:{couponId}
     *            field: count       value:
     *            field: userLimit   value:
     *            field: growthLimit value:
     * ----------------------------------------
     *     key: userSeckillCoupon:{couponId}
     *          field: {userId}     value: 该用户秒杀过的数量
     *          ...                 ...
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie userTicketCookie = Arrays.stream(request.getCookies())
                .filter(cookie -> cookie.getName().equals("userTicket"))
                .findFirst().get();
        String userTicket = userTicketCookie.getValue();
        Boolean isUser = redisTools.exists("user:"+userTicket).getData();
        if (isUser){
            throw new InterceptorException(ErrorCode.NOT_LOGIN);
        }
        String couponId = request.getParameter("couponId");
        String userId = (String) redisTools.hget("user:"+userTicket,"id").getData();
        Boolean isSeckillCoupon = redisTools.exists("seckillCoupon:"+couponId).getData();
        if (!isSeckillCoupon){
            throw new InterceptorException(403,"秒杀的商品不存在");
        }
        Map<Object, Object> map = redisTools.hgetall("seckillCoupon:"+couponId).getData();
        Integer residueCount = (Integer) map.get("count");
        if (residueCount!=-1 && residueCount<1){
            throw new InterceptorException(403,"该商品已经秒杀完");
        }
        Long growth = (Long) redisTools.hget("user:"+userTicket,"growth").getData();
        Long growthLimit = (Long) map.get("growthLimit");
        if (growth < growthLimit){
            throw  new InterceptorException(403,"用户成长值达不到购买优惠券资格");
        }
        Integer userLimit = (Integer) map.get("userLimit");
        Boolean userExists = redisTools.stringRedisTemplate.opsForHash().hasKey("userSeckillCoupon:"+couponId,userId);
        Integer userSeckillCount = 0;
        if (userExists){
            userSeckillCount = (Integer) redisTools.hget("userSeckillCoupon:"+couponId,userId).getData();
            if (userLimit!=-1 && userSeckillCount>=userLimit){
                throw new InterceptorException(403,"该用户的秒杀请求数量已经超过领取上限");
            }
        }
        Map<String,Integer> incrMap =new HashMap<>();
        incrMap.put(userId,userSeckillCount+1);
        redisTools.hset("userSeckillCoupon:"+couponId,incrMap);
        return true;
    }
}
